<?php

class Location extends AppModel {

    public $actsAs = array('Tree', 'Containable');
    public $name = 'Location';
    public $useTable = 'location';
    public $primaryKey = 'location_id';
    public $hasMany = array(
        'location_language' => array(
            'className' => 'Locationlanguage',
            'foreignKey' => 'location_id',
        )
    );

    /**
     * get child tree
     * @param array $data
     * @param type $parentId
     * @param type $ht
     * @param type $char
     */
    public function loop(&$data, $parentId, $start, $char = "_") {
        App::import('model', 'Locationlanguage');
        $ob = new Locationlanguage();
        $name = $ob->find('first', array('conditions' => array('Locationlanguage.location_id' => $parentId, 'Locationlanguage.language_id' => Configure::read('Config.language'))));
        $data[$parentId] = $start . $name['Locationlanguage']['name'];
        $con = $this->children($parentId, true);
        foreach ($con as $value) {
            //print_r($con);exit;
            $this->loop($data, $value['Location']['location_id'], $start . $char);
        }
    }

    /**
     * get list tree
     * @param type $locationId
     * @return array
     */
    public function createTree($locationId = 1) {
        $data = array();
        $this->loop($data, $locationId, "");
        return $data;
    }

    public function loopV2(&$data, $parentId, $start, $char = " ") {
        App::import('model', 'Locationlanguage');
        $ob = new Locationlanguage();
        $name = $ob->find('first', array('conditions' => array('Locationlanguage.location_id' => $parentId, 'Locationlanguage.language_id' => Configure::read('Config.language'))));
        $data[$parentId] = $start . $name['Locationlanguage']['name'];
        $con = $this->children($parentId, true);
        foreach ($con as $value) {
            //print_r($con);exit;
            $this->loop($data, $value['Location']['location_id'], $start . $char);
        }
    }

    public function createTreeV2($locationId = 1) {
        $data = array();
        $this->loopV2($data, $locationId, "");
        unset($data[1]);
        return $data;
    }

    /**
     * 
     * @param type $created
     * @param type $options
     */
    public function afterSave($created, $options = array()) {
        parent::afterSave($created, $options);
        App::import('model', 'Locationlanguage');
        App::import('model', 'Language');
        $ob = new Locationlanguage();
        $data = $this->data;
        if ($created) {
            $data['Locationlanguage']['location_id'] = $data['Location']['location_id'];
            foreach (Language::getList() as $language) {
                $ob->create();
                $data['Locationlanguage']['language_id'] = $language;
                $ob->save($data);
            }
        } else {
            if ($data['Location']['location_id']) {
                $data['Locationlanguage']['language_id'] = Configure::read('Config.language');
                $data['Locationlanguage']['location_id'] = $data['Location']['location_id'];
                if ($id = $ob->findPrimaryKey(array('Locationlanguage.language_id' => Configure::read('Config.language'), 'Locationlanguage.location_id' => $data['Location']['location_id']))) {
                    $ob->id = $id;
                    $ob->save($data);
                }
            }
        }
    }

    /**
     * 
     * @param type $options
     * @return boolean
     */
    public function beforeSave($options = array()) {
        parent::beforeSave($options);
        App::import('model', 'Locationlanguage');
        $ob = new Locationlanguage();
        $ob->set($this->data);
        if ($ob->validates()) {
            return true;
        }
        return false;
    }

    public static function generateRow($parentId, &$out, $star, $char = " - ") {
        $ob = new Location();
        $ob->hasMany['location_language']['conditions'] = array('location_language.language_id' => Configure::read('Config.language'));
        $value = $ob->findBylocation_id($parentId);
        if (isset($value['Location']['parent_id'])) {
            $parentname_qr = $ob->query("SELECT location_language.`name` as `name` 
                            FROM `location_language`
                            WHERE location_language.location_id = " . $value['Location']['parent_id'] . " 
                            AND language_id = '" . Configure::read('Config.language') . "'");
            $parentname = isset($parentname_qr[0]['location_language']['name']) ? $parentname_qr[0]['location_language']['name'] : '';
        } else {
            $parentname = '';
        }
        $delete_location = '';
        if ($value['Location']['location_id'] != 1) {
            $delete_location = " | <a href='" . Router::url("/", true) . "location/deletelocation/" . $value['Location']['location_id'] . "'>" . __('Delete') . "</a>";
        }
        $out .= "<tr>
                    <td>" . $value['Location']['location_id'] . "</td>
                    <td>" . $star . $value['location_language'][0]['name'] . "</td>
                    <td>" . $parentname . "</td>
                    <td>" . date('Y-m-d', strtotime($value['Location']['created'])) . "</td>
                    <td><a href='" . Router::url("/", true) . "location/addlocation/" . $value['Location']['location_id'] . "'>" . __('Edit') . "</a>
                        " . $delete_location . "</td>
                  </tr>";
        $con = $ob->children($parentId, true);
        foreach ($con as $value) {
            $ob->generateRow($value['Location']['location_id'], $out, $star . $char);
        }
    }

    /**
     * Get cateogry byID
     * @param type $getLocationID
     * @return boolean
     */
    public function getLocationID($locationID) {
        $ob = new Location();
        $ob->hasMany['location_language']['conditions'] = array('location_language.language_id' => Configure::read('Config.language'));
        $result = $ob->findBylocation_id($locationID);
        if ($result) {
            $result['Locationlanguage'] = $result['location_language'][0];
            return $result;
        }
        else
            return false;
    }

    public function loopSearch(&$data, $parentId, $start, $char = "") {
        App::import('model', 'Locationlanguage');
        $ob = new Locationlanguage();
        $name = $ob->find('first', array('conditions' => array('Locationlanguage.location_id' => $parentId, 'Locationlanguage.language_id' => Configure::read('Config.language'))));
        $data[$parentId] = $start . $name['Locationlanguage']['name'];
        $con = $this->children($parentId, true);
        foreach ($con as $value) {
            $this->loopSearch($data, $value['Location']['location_id'], $start . $char);
        }
    }

    public function createSearch($locationId = 1) {
        $data = array();
        $sql_parent = "SELECT * 
            FROM location, location_language
            WHERE location.parent_id =" . ID_LOCATION_ROOT . "
            and location.location_id = location_language.location_id
            and location_language.language_id = '" . Configure::read('Config.language') . "'";
        //echo "<pre>";var_dump($sql_parent);die();
        $results = $this->getDataSource()->fetchAll($sql_parent);
        if (is_array($results)) {
            foreach ($results as $category_parent) {

                $sql = "SELECT location_language.* 
                    FROM location, location_language
                    WHERE location.parent_id ='" . $category_parent['location']['location_id'] . "'
                    and location.location_id = location_language.location_id
                    and location_language.language_id = '" . Configure::read('Config.language') . "'";
                $results_record = $this->getDataSource()->fetchAll($sql);
                $array_new = array();
                if (is_array($results_record)) {
                    foreach ($results_record as $val) {
                        $array_new[$val['location_language']['location_id']] = $val['location_language']['name'];
                    }
                }
                $data[$category_parent['location_language']['location_id']] = array('name' => $category_parent['location_language']['name'], 'list_category' => $array_new,);
            }
        }

        return $data;
    }

    /**
     * 
     */
    public function getListChild($location_id) {
        $array_new_data = array();
        $list = $this->children($location_id, true);
        if (is_array($list)) {
            foreach ($list as $value) {
                $array_new_data[] = $value['Location']['location_id'];
            }
        }
        return $array_new_data;
    }

}
